package assets_service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"mime/multipart"
	"path"
	"path/filepath"
	"shimmer/neusoft_club_backend/controllers/utils"
	"shimmer/neusoft_club_backend/dao/domain"
	"shimmer/neusoft_club_backend/services"
	"strconv"
	"time"
)

type SaveUploadAssetMutation struct {
	OwnerID *int64
}

func FindAssetById(id int64) (res *domain.Assets, err error) {
	res = &domain.Assets{ID: id}
	err = services.DBEngine.First(res).Error
	return
}

func FindAssets(where map[string]interface{},pageQuery *utils.PaginationQuery) (res utils.Pagination,err error) {
	db := services.BuildWhere(where,services.DBEngine)
	assets := &[]domain.Assets{}
	res,err = utils.QueryAndPaginate(pageQuery,db,assets)
	return
}

func CreateForeignAssets(url string, db *gorm.DB) (res *domain.Assets, err error) {
	res = &domain.Assets{
		Path:      url,
		IsForeign: true,
	}
	err = db.Save(res).Error
	return
}

func SaveUploadAsset(file *multipart.FileHeader, c *gin.Context, mutation *SaveUploadAssetMutation) (res *domain.Assets, err error) {
	ownerID := mutation.OwnerID
	file.Filename = fmt.Sprintf("%s%s", strconv.FormatInt(time.Now().Unix(), 10), path.Ext(file.Filename))
	dst, err := filepath.Abs(FileUploadBasePath)
	err = c.SaveUploadedFile(file, path.Join(dst, file.Filename))
	if err != nil {
		return
	}
	config := services.ConfigServiceInstance
	res = &domain.Assets{
		Path:      config.Path.Public + path.Join(PublicUploadBasePath, file.Filename),
		IsForeign: false,
		OwnerID:   ownerID,
	}
	if err = services.DBEngine.Save(res).Error; err != nil {
		return
	}
	return
}

func ShuffleAssets(count int) (res []*domain.Assets, err error) {
	res = make([]*domain.Assets, 0)
	avatarAssets := make([]*domain.AvatarAssets, 0)

	if err = services.DBEngine.Order("RAND()").Joins(domain.AvatarAssetsFieldAssets).Limit(count).Find(&avatarAssets).Error; err != nil {
		return
	}
	for _, item := range avatarAssets {
		res = append(res, &item.Assets)
	}
	return
}
